package com.camtc.camcenter.util;

import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.setting.dialect.Props;
import cn.hutool.setting.dialect.PropsUtil;
import com.camtc.camcenter.property.ApplicationProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Import;

import java.util.concurrent.atomic.AtomicReference;

/**
 * <p>
 * 属性文件操作
 * </p>
 *
 * @author chentianshun
 * @since 2021-07-28
 */
@Slf4j
@Import({SpringUtil.class})
public class PropertyUtils {
    private final static String DEFAULT_RES = "application.properties";

    /**
     * 属性文件Key 取得
     * 默认取 application.properties
     *
     * @param resKey
     * @return
     */
    public static int getIntProperty(String resKey) {
        return Integer.parseInt(getString(resKey, DEFAULT_RES));
    }

    /**
     * 属性文件Key 取得
     * 默认取 application.properties
     *
     * @param resKey
     * @return
     */
    public static String getProperty(String resKey) {
        return getString(resKey, DEFAULT_RES);
    }

    /**
     * 属性文件Key 取得
     *
     * @param resourcePath
     * @param resKey
     * @return
     */
    public static String getProperty(String resourcePath, String resKey) {
        return getString(resKey, resourcePath);
    }

    /**
     * 取得实现
     *
     * @param resKey
     * @param defaultRes
     * @return
     */
    private static String getString(String resKey, String defaultRes) {
        AtomicReference<String> rtnStr = new AtomicReference<>("");
        try {
            ApplicationProperties properties = SpringUtil.getBean(ApplicationProperties.class);
            rtnStr.set(properties.getProperty(resKey));
        } catch (Exception exception) {
            Props props = PropsUtil.get(DEFAULT_RES);
            rtnStr.set(props.getProperty(resKey));
        }
        return rtnStr.get();
    }
    /**
     * 属性文件Key 取得
     * 默认取 application.properties
     *
     * @param resKey
     * @return
     */
    public static boolean getBooleanProperty(String resKey,String resource) {
        return Boolean.parseBoolean(getString(resKey, resource));
    }

}

